#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "mtd.h"
#include "nand.h"
#include "mtd_sim.h"
#include "yaffs_guts.h"

/** 
 * XXX: global variables are not properly used here!
 */

#define CHUNKSIZE 2048
#define SPARESIZE 64
#define CHUNKSPERBLOCK 64

unsigned int chunkSize = CHUNKSIZE;
unsigned int spareSize = SPARESIZE;
unsigned int chunksPerBlock = CHUNKSPERBLOCK;
unsigned int totalBytesPerBlock = 0;
unsigned int totalBytesPerChunk = 0;
unsigned int dataBytesPerBlock = 0;
unsigned int totalBlocks = 0;
unsigned int totalChunks = 0;
unsigned int totalSize = 0;

int
mtd_sim_init(struct mtd_info *mtd, char *img_file_name)
{
	struct stat img_stat;
	int r, fd_img;
	if ((r = stat(img_file_name, &img_stat)) < 0)
		return r;
	if (!S_ISREG(img_stat.st_mode))
		return -1;

	totalSize = img_stat.st_size;
	totalBytesPerChunk = chunkSize + spareSize;
	totalBytesPerBlock = totalBytesPerChunk * chunksPerBlock;

	if (totalSize % totalBytesPerChunk)
		return -1;

	dataBytesPerBlock = chunkSize * chunksPerBlock;
	totalChunks = totalSize / totalBytesPerChunk;
	totalBlocks = totalSize / (totalBytesPerChunk*chunksPerBlock);
	totalChunks % chunksPerBlock ?  0 : ++totalBlocks;

	fd_img = open(img_file_name, O_RDONLY, S_IREAD);
	if (fd_img < 0)
		return fd_img;

	nand_init(mtd);
	nand_read_img(fd_img, totalSize);
//	printf("Read NAND image complete!");
	return 0;
}

